import 'package:bilibili_getx/core/constant_util/size.dart';
import 'package:bilibili_getx/ui/middle_ware/login_auth_middle_ware.dart';
import 'package:bilibili_getx/ui/pages/main/home/comic/comic_view.dart';
import 'package:bilibili_getx/ui/pages/main/home/recommend/recommend_view.dart';
import 'package:bilibili_getx/ui/pages/main/home/search/search_view.dart';
import 'package:bilibili_getx/ui/pages/main/main_logic.dart';
import 'package:bilibili_getx/core/constant_util/app_theme.dart';
import 'package:bilibili_getx/ui/pages/main/main_view.dart';
import 'package:bilibili_getx/ui/widgets/custom/circle_inkwell_button.dart';
import 'package:bilibili_getx/ui/widgets/custom/primary_scroll_container.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../../core/I18n/str_res_keys.dart';
import '../../../shared/image_asset.dart';
import 'home_logic.dart';
import 'live/live_view.dart';

class HomeScreen extends StatefulWidget {
  static const String routeName = "/home";

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen>
    with
        SingleTickerProviderStateMixin,
        SizeConstantUtil,
        HYAppTheme,
        ImageAssets {
  final logic = Get.find<HomeLogic>();
  final state = Get.find<HomeLogic>().state;
  late TabController tabBarC;

  @override
  void initState() {
    tabBarC = TabController(length: 7, vsync: this, initialIndex: 1);
    tabBarC.addListener(() {
      for (int i = 0; i < state.scrollChildKeys.length; i++) {
        GlobalKey<PrimaryScrollContainerState> key = state.scrollChildKeys[i];
        if (key.currentState != null) {
          key.currentState?.onPageChange(tabBarC.index == i); //控制是否当前显示
        }
      }
    });
    logic.initHomeUserInfo();

    ///判断是否同意用户协议
    if (!state.tempUserAgreement) {
      logic.initUserAgreement();
    }

    ///判断是否同意青少年模式
    if (!state.tempTeenagerMode && state.tempUserAgreement) {
      logic.showTeenagerModeDialog();
    }
    Future.delayed(const Duration(seconds: 1), () {
      logic.initHomeSliverAppBarHeightY();
    });

    ///搜索推荐关键字
    logic.getHomeSearchKey();
    super.initState();
  }

  @override
  void dispose() {
    tabBarC.removeListener(() {});
    tabBarC.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildWhiteStatusBar(),
      body: NestedScrollView(
        headerSliverBuilder: (ctx, innerBoxIsScrolled) {
          return [
            SliverToBoxAdapter(child: buildHomeTopAppBar()),
            SliverAppBar(
              title: buildHomeTabBar(),
              pinned: true,
              floating: false,
              snap: false,
              surfaceTintColor: norWhite01Color,
              backgroundColor: norWhite01Color,
              shadowColor: norWhite01Color,
              elevation: 0,
            ),
          ];
        },
        body: buildHomeTabBarView(),
      ),
    );
  }

  /// 顶部状态栏为白色
  buildWhiteStatusBar() {
    return AppBar(
      systemOverlayStyle: whiteTheme,
      toolbarHeight: 0,
      elevation: 0,
    );
  }

  ///用户头像 / 搜索 / 右侧按钮
  Widget buildHomeTopAppBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.r, vertical: 5.r),
      width: 1.sw,
      color: norWhite01Color,
      child: Row(
        children: [
          buildHomeUserIcon(),
          Expanded(child: buildSearchTextField()),
          CircleInkWellButton(
            bgColor: norWhite06Color,
            onTap: () {},
            width: 40.r,
            height: 40.r,
            child: Image.asset(
              gameCustomPNG,
              width: iconSizeCons.r,
              height: iconSizeCons.r,
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15.r),
            child: Image.asset(
              width: iconSizeCons.r,
              height: iconSizeCons.r,
              mailCustomPNG,
            ),
          ),
        ],
      ),
    );
  }

  /// 搜索框
  Widget buildSearchTextField() {
    return GestureDetector(
      onTap: () {
        Get.toNamed("${MainView.routeName}${HomeSearchView.routeName}");
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 15.r),
        alignment: Alignment.centerLeft,
        height: 35.r,
        decoration: BoxDecoration(
          color: norWhite02Color,
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.r),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                margin: EdgeInsets.symmetric(horizontal: 10.r),
                child: Image.asset(
                  searchCustomPNG,
                  width: iconSizeCons.r,
                  height: iconSizeCons.r,
                  color: norGray02Color,
                ),
              ),
              GetBuilder<HomeLogic>(
                builder: (logic) {
                  return Text(
                    state.firstSearchKey.isNotEmpty
                        ? state.firstSearchKey.value
                        : SR.searching.tr,
                    style: TextStyle(
                      fontSize: subTitleFontSizeCons.r,
                      color: norGray02Color,
                      overflow: TextOverflow.ellipsis,
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  ///主页 顶部TabBar
  Theme buildHomeTabBar() {
    return Theme(
      data: Theme.of(context).copyWith(
        colorScheme: ColorScheme.light(
          primary: norMainThemeColors,
          surface: norWhite01Color,
        ),
      ),
      child: TabBar(
        tabAlignment: TabAlignment.start,
        controller: tabBarC,
        tabs: [
          Tab(text: SR.live.tr.toUpperCase()),
          Tab(text: SR.recommend.tr.toUpperCase()),
          Tab(text: SR.hot.tr.toUpperCase()),
          Tab(text: SR.comic.tr.toUpperCase()),
          Tab(text: SR.movie.tr.toUpperCase()),
          Tab(text: SR.covid.tr.toUpperCase()),
          Tab(text: SR.journey.tr.toUpperCase()),
        ],
        indicatorPadding:
            EdgeInsets.only(bottom: 10.r, left: 15.r, right: 15.r),
        indicatorColor: norMainThemeColors,
        unselectedLabelColor: unselectedLabelColor,
        labelColor: norMainThemeColors,
        indicatorSize: TabBarIndicatorSize.tab,
        labelStyle: TextStyle(
          fontSize: selectTabFontSizeCons.r,
          fontWeight: FontWeight.normal,
          color: norMainThemeColors,
          fontFamily: bF,
        ),
        unselectedLabelStyle: TextStyle(
          fontSize: unSelectTabFontSizeCons.r,
          fontWeight: FontWeight.normal,
          color: norTextColors,
          fontFamily: bF,
        ),
        isScrollable: true,
      ),
    );
  }

  ///home中主要显示的内容，与tabBar对应
  Widget buildHomeTabBarView() {
    ///未同意用户协议
    return state.tempUserAgreement
        ? TabBarView(
            controller: tabBarC,
            children: [
              PrimaryScrollContainer(
                key: state.scrollChildKeys[0],
                child: const LiveScreen(),
              ),
              PrimaryScrollContainer(
                key: state.scrollChildKeys[1],
                child: HomeRecommendView(),
              ),
              PrimaryScrollContainer(
                key: state.scrollChildKeys[2],
                child: Container(),
              ),
              PrimaryScrollContainer(
                key: state.scrollChildKeys[3],
                child: ComicScreen(),
              ),
              PrimaryScrollContainer(
                key: state.scrollChildKeys[4],
                child: Container(),
              ),
              PrimaryScrollContainer(
                key: state.scrollChildKeys[5],
                child: Container(),
              ),
              PrimaryScrollContainer(
                key: state.scrollChildKeys[6],
                child: Container(),
              ),
            ],
          )
        : Container();
  }

  ///圆形图标（登录图标
  Widget buildHomeUserIcon() {
    return state.userLogo.isEmpty
        ? CircleInkWellButton(
            bgColor: norWhite06Color,
            onTap: () {
              LoginWidget().goToLogin();
            },
            width: 40.r,
            height: 40.r,
            child: Text(
              SR.login.tr,
              textAlign: TextAlign.center,
              maxLines: 1,
              style: TextStyle(
                fontWeight: FontWeight.normal,
                color: norMainThemeColors,
                fontSize: customFontSizeCons.r,
                fontFamily: bF,
              ),
            ),
          )
        : GestureDetector(
            onTap: () {
              ///点击已登录头像，更新mainScreen的底部导航栏下标
              final logic = Get.find<MainLogic>();
              logic.updateCurrentIndex(4);
            },
            child: CircleAvatar(
              backgroundImage: NetworkImage(state.userLogo),
              radius: 18.r,
            ),
          );
  }
}
